<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of membersModule
 *
 * @author dionisrom
 */
class membersModule extends LoadConfigs
{
	public function __construct() {
	}

	public function isValidMember()
	{
		$params = $this->getAllParams();
		if (array_key_exists("username", $params) && array_key_exists("password", $params)) {
			$results = $this->_validate($params);
			if ($results["username"]["valid"] && $results["password"]["valid"]) {
				$getMemberSql = "	SELECT * FROM ::table:: 
									WHERE username = '::username::' and 
										  password = '::password::'";
				$params = array (
					"table"		=> "members",
					"username"	=> "" . $params["username"],
					"password"	=> "" . md5($params["password"])
				);
				$dbObj = new dBModule;
				$user = $dbObj->selectOneRow($getMemberSql, $params);
				return $user;
			}
		}
		
		return false;
	}
	
	public static function memberLogin($params)
	{
		$sql = "SELECT * FROM ::table:: WHERE username = '::username::' and password = '::password::'";
		$params = array_merge(
				array( 'table' => 'members'),
				$params
				);
		$dbObj = new dBModule;
		$response = $dbObj->selectOneRow($sql, $params);
		if ($response) {
			$this->_createMemberSession();
			return true;
		}
		return false;
	}
	
	private function _createMemberSession()
	{
		if (isset($_COOKIE["member"])){
			$cookieMemberInfo = $_COOKIE["member"];
			$isValid = $this->_validate($cookieMemberInfo);
			if (count(array_keys($isValid, true)) == count($isValid)) {
				$_SESSION["member"] = $cookieMemberInfo;
				return true;
			}
		} 
		$result = $this->isValidMember();
		if (is_array($result)) {
			$_SESSION["member"] = $result;
			$_COOKIE["member"] = $result;
			return true;
		}
		return false;
	}
	
	private function get($key = null)
	{
		$membersInfo = $_SESSION["member"];
		if (isset($membersInfo) && array_key_exists($key, $membersInfo)) {
			return $key;
		}
	}
	
	public function getFullName() 
	{
		$familyName = $this->get("family_name"); 
		$lastName = $this->get("last_name"); 
		return $lastName . " " . $familyName;
	}
	
	public function getEmail()
	{
		$email = $this->get("email");  
		return $email;
	}
	
	public function getFullAddress()
	{
		$street = $this->get("street");
		$streetNr = $this->get("street_nr");
		$postalCode = $this->get("postal_code");
		$city = $this->get("city");
		return $streetNr . ", " . $street . ", " . $postalCode . ", " . $city;
	}
	
	private function _memberExist($username = null)
	{
		if (!empty($username)) {
			$sql = "SELECT * FROM ::table:: WHERE username = ::username::";
			$params = array(
				"table"	=> "members",
				"username" => "" . $username
			);
			return $this->dbObject->selectOneRow($sql, $params);
		}
		
		return false;
	}
	
	private function _emailExist($email = null)
	{
		if (!empty($email)) {
			$sql = "SELECT * FROM ::table:: WHERE email = ::email::";
			$params = array(
				"table"	=> "members",
				"email" => "" . $email
			);
			return $this->dbObject->selectOneRow($sql, $params);
		}
		
		return false;
	}

	public function ajaxInsertMember($params)
	{
		$validationResult = $this->_validate($params);
		if (count(array_keys($validationResult, true)) != count($validationResult)) {
			$validationResult = array_merge(
					array(
						"result" => false,
						"message" => null
					)
					, $validationResult);
			echo json_encode($validationResult);
			return false;
		}
		
		if (!$this->_memberExist($params["member"]) && !$this->_emailExist($params["email"])) {
			$sqlInsert = "INSERT INTO ::table:: 
				(family_name, last_name, email, username, email, username, password, street, street_nr, postal_code, city, phone) 
				VALUES 
				(::family_name::, ::last_name::, ::email::, ::username::, ::email::, ::username, ::password::, ::street::, ::street_nr::, ::postal_code::, ::city::, ::phone::)";
			$params = array_merge(array("table" => "members"), $params);
			$result = $this->dbObject->execute($sqlInsert, $params);
			if ($result) {
				$return = array(
					"result" => true,
					"message" => "Member was created succesfully!"
				);
			} else {
				$return = array(
					"result" => false,
					"message" => "An errror appears on insert action!"
				);
			}
			echo json_encode($return);
		} else {
			$response = array(
				"result" => false,
				"message" => "Member or email already exists!"
			);
			echo json_encode($response);
		}
		return false;
	}

	private function _validate(array $params = array())
	{
		$response = array();
		foreach ($params as $key => $value) {
			switch ($key) {
				case 'username':
					$regExp			= "/^[a-zA-Z\s0-9]+$/";
					$element		= "Username";
					$mustContain	= "Your username must contain only letters and numbers";
					break;
				case 'password':
					$regExp			= "/^[a-zA-Z\s0-9]+$/";
					$element		= "Password";
					$mustContain	= "Your username must contain only letters and numbers";
					break;
				case 'street':
					$regExp			= "/^[a-zA-Z\s]+$/";
					$element		= "Street";
					$mustContain	= "Your username must contain only letters";
					break;
				case 'city':
					$regExp			= "/^[a-zA-Z\s]+$/";
					$element		= "City";
					$mustContain	= "Your city must contain only letters";
					break;
				case 'street_nr':
					$regExp			= "/^[0-9]+$/";
					$element		= "Street number";
					$mustContain	= "Your ustreet number must contain only numbers";
					break;
				case 'email':
					$regExp			= '^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$';
					$element		= "email";
					$mustContain	= "";
					break;
				case 'postal_code':
					$regExp			= '([a-zA-Z])\d([a-zA-Z])(.?)\d([a-zA-Z])\d';
					$element		= "postal code";
					$mustContain	= "";
					break;
				case 'phone':
					$regExp			= '^[2-9]\d{2}-\d{3}-\d{4}$';
					$element		= "phone";
					$mustContain	= "";
					break;
			}
			$response[$key]["valid"] = (preg_match($regExp, $value)  == 1) ? true : false ;
			$response[$key]["message"] = (empty($value)) ? "You have to enter a value for  $element field!" : "Your $element is invalid!";
		}
		
		return $response;
	}
}

?>
